from flask import Flask, jsonify, request
from flask_cors import CORS
from cofing import Cofing
from logging import FileHandler
from views.comany import bp_company
from views.users import bp_user
import logging
from utlis.acl import acll
from utlis.jwt_token import myjwt

import datetime


def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app
app = create_app()


CORS(app)
app.config.from_object(Cofing)
app.register_blueprint(bp_company)
app.register_blueprint(bp_user)


# 请求前
@app.before_request
def before_request():
    white = ["/loginM"]
    try:
        #获取token
        token = request.headers.get("Token")
        # print(token)
    except:
        token = None
    if token:
        #解密token
        user = myjwt.jwt_decode(token)
        # print(user)
        if user:
            #找出token中我存的userid
            aa = user['data']['userid']
            #放到acl中查找需要的接口
            reslist = acll.get_flask(int(aa))
            # print(reslist)
            for i in reslist:
                white.append(i)
            print(white)
            #在with中查找有没有这个接口
            if request.path not in white:
                print(request.path)
                return jsonify({"code":403,"msg":"没有权限访问"})
        else:
            return jsonify({"code":40312,"msg":"你的token有问题"})
    else:
        if request.path not in white:
            return jsonify({"code":40311,"msg":"没有token"})


if __name__ == '__main__':
    filename = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m')
    handler = logging.FileHandler("logs/"+filename+".txt")
    app.logger.addHandler(handler)
    app.run(debug=True)
